<?php

/**
 * 世界杯
 * @date 2022-10-18
 */

namespace app\admin\controller;

use app\common\model\MatchesScheduleModel;
use app\common\model\WorldCupMatchModel;
use app\common\model\WorldCupMatchRankModel;
use app\common\model\WorldCupPointModel;
use app\common\model\WorldCupRankModel;
use think\Db;
use think\facade\Request;
use think\Validate;


class WorldcupController extends BaseController
{

    /**
     * 赛事首页
     * @return mixed
     */
    public function index()
    {
        $day_arr    = array();
        $start_time = strtotime('2024-06-15');
        $end_time   = strtotime('2024-07-15');
        $week       = ['周日', '周一', '周二', '周三', '周四', '周五', '周六',];

        for ($i = 0; $i < 30; $i++) {
            $time = $start_time + ($i * 3600 * 24);
            if ($time > $end_time) {
                break;
            }
            $day_arr[] = [
                'date'   => date('Y-m-d', $time),
                'day'    => date('m/d', $time),
                'week'   => $week[date('w', $time)],
                'active' => $time == strtotime('Y-m-d') ? date('Y-m-d') : date('Y-m-d', $start_time),
            ];
        }
        $day_arr = array_chunk($day_arr, 7);

        // 锁定当前日期和第几周
        $now_day    = strtotime(date('Y-m-d'));
        $now_num = floor((($now_day - $start_time) / 3600 / 24) / 7);
        $active_day = $now_day >= $start_time && $now_day <= $end_time ? date('Y-m-d', $now_day) : date('Y-m-d', $start_time);

        $this->assign('day_arr', $day_arr);
        $this->assign('now_num', $now_num);
        $this->assign('active_day', $active_day);
        return $this->fetch();
    }

    /**
     * 赛事列表
     * @return \think\response\Json
     */
    public function getlist()
    {
        $date = Request::get('date');
        if (empty($date)) {
            return self::bulidFail("未查询到相关数据");
        }

        $list = WorldCupMatchModel::with('matchInfo')->where('match_date', $date)->select();
        if (count($list) > 0) {
            foreach ($list as &$item) {
                $item->match_hour = date('H:i', $item->match_time);
            }
            return self::bulidSuccess($list);
        }
        return self::bulidFail("未查询到相关数据");
    }

    /**
     * 添加赛事
     * @return \think\response\Json
     */
    public function add()
    {

        if (Request::isPost()) {
            $all_param = Request::param();

            $validate = new Validate([
                'match_id' => 'require|number',
            ], [
                "match_id" => "请选择赛事",
            ]);

            if (!$validate->check($all_param)) {
                return self::bulidFail($validate->getError());
            }
            // 查询赛事
            $match_info = MatchesScheduleModel::with('footballmatch')->where('match_id', $all_param['match_id'])->find();
            if (!$match_info) {
                return self::bulidFail('未查询到相关比赛');
            }
            // 赛事信息
            $football_match = $match_info->footballmatch;

            $data = [
                'match_id'       => $match_info->match_id,
                'venue_name'     => @$football_match->venue ? @$football_match->venue->name_zh : '',
                'venue_name_en'  => @$football_match->venue ? @$football_match->venue->name_en : '',
                'group_code'     => isset($all_param['group']) ? strtoupper($all_param['group']) : '',
                'home_team_id'   => $football_match->home_team_id ?? 0,
                'home_team_name' => $match_info->home,
                'home_team_logo' => $football_match->hometeam ? $football_match->hometeam->country_logo : $match_info->home_logo,
                'away_team_id'   => $football_match->away_team_id ?? 0,
                'away_team_name' => $match_info->away,
                'away_team_logo' => $football_match->awayteam ? $football_match->awayteam->country_logo : $match_info->away_logo,
                'status_id'      => $match_info->match_status,
                'time_played'    => $match_info->time_played,
                'match_time'     => $match_info->match_time,
                'match_date'     => date('Y-m-d', $match_info->match_time),
                'home_scores'    => $match_info->home_score,
                'away_scores'    => $match_info->away_score,
            ];

            // 查询比赛是否有写入
            $world_cup_match = WorldCupMatchModel::where('match_id', $all_param['match_id'])->find();


            if (!$world_cup_match) {
                $world_cup_match = new WorldCupMatchModel();
            }

            if ($world_cup_match->save($data)) {
                // 记录日志
                $log_content = "添加世界杯赛事，球队：{$data['home_team_name']} VS {$data['away_team_name']}";
                parent::addAdminLog($log_content);

                return parent::bulidSuccess();
            }
            return parent::bulidFail();
        }

        // 获取世界杯赛事
        $where      = [
            ['sport_id', '=', 1],
            ['comp_short_zh', '=', '欧洲杯'],
            ['match_time', '>', 1717200000]
        ];
        $match_list = MatchesScheduleModel::where($where)->select()->each(function ($query) {
            $query->match_time_str = date('Y-m-d H:i:s', $query->match_time);
        });
        $this->assign('match_list', $match_list);
        return $this->fetch();
    }

    /**
     * 球队积分
     */
    public function point()
    {
        return $this->fetch();
    }

    /**
     * 球队积分列表
     * @return \think\response\Json
     */
    public function point_list()
    {
        $group = Request::get('group');
        if (empty($group)) {
            return self::bulidFail("未查询到相关数据");
        }

        $list = WorldCupPointModel::where('group_code', $group)->select();
        if (count($list) > 0) {
            foreach ($list as &$item) {
                // 场均进球率
                $item->goal_rate = $item->match_times > 0 ? bcdiv($item->goals, $item->match_times, 2) : 0;
                // 场均失球率
                $item->fumble_rate = $item->match_times > 0 ? bcdiv($item->goals_conceded, $item->match_times, 2) : 0;
                // 场均净胜球
                $item->goal_difference_rate = $item->match_times > 0 ? bcdiv($item->goal_difference, $item->match_times, 2) : 0;
            }
            return self::bulidSuccess($list);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function point_add()
    {
        $match_list = WorldCupMatchModel::where("group_code!=''")->select();

        $matches = [];
        foreach ($match_list as $key => $value) {
            $matches[] = ['team_id' => $value['home_team_id'], 'team_name' => $value['home_team_name'], 'team_logo' => $value['home_team_logo']];
            $matches[] = ['team_id' => $value['away_team_id'], 'team_name' => $value['away_team_name'], 'team_logo' => $value['away_team_logo']];
        }

        $this->assign('match_list', $matches);
        return $this->fetch();
    }

    public function point_add_handle()
    {

        $all_param = Request::param();

        $validate = new Validate([
            'team'  =>  'require',
            'match_times'            => 'require|number',
            'win'            => 'require|number',
            'draw'           => 'require|number',
            'lost'           => 'require|number',
            'goals'          => 'require|number',
            'goals_conceded' => 'require|number',
            'score'          => 'require|number',
        ], [
            'match_times'            => "请正确输入场次",
            'team'            => "请选择球队",
            'win'            => "请正确输入胜利场数",
            'draw'           => '请正确输入平局场数',
            'lost'           => '请正确输入失败场数',
            'goals'          => '请正确输入进球总数',
            'goals_conceded' => '请正确输入失球总数',
            'score'          => '请正确输入总积分',
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $model = new WorldCupPointModel($all_param);

        $team = explode("|", $all_param['team']);
        $model->team_id = $team[0];
        $model->team_name = $team[1];
        $model->team_logo = $team[2];

        if ($model->save($all_param)) {
            return parent::bulidSuccess();
        }
        return parent::bulidFail();
    }

    /**
     * 编辑球队积分
     * @return \think\response\Json
     */
    public function point_edit()
    {
        $id         = Request::param('id');
        $point_info = WorldCupPointModel::get($id);
        if (!$point_info) {
            return self::bulidFail("未查询到相关数据");
        }

        if (Request::isPost()) {
            $all_param = Request::param();

            $validate = new Validate([
                'match_times'            => 'require|number',
                'win'            => 'require|number',
                'draw'           => 'require|number',
                'lost'           => 'require|number',
                'goals'          => 'require|number',
                'goals_conceded' => 'require|number',
                'score'          => 'require|number',
            ], [
                'match_times'            => "请正确输入场次",
                'win'            => "请正确输入胜利场数",
                'draw'           => '请正确输入平局场数',
                'lost'           => '请正确输入失败场数',
                'goals'          => '请正确输入进球总数',
                'goals_conceded' => '请正确输入失球总数',
                'score'          => '请正确输入总积分',
            ]);

            if (!$validate->check($all_param)) {
                return self::bulidFail($validate->getError());
            }

            //胜平负的场次之和不能超过3场
            // $all_param['match_times'] = intval(($all_param['win'] + $all_param['draw'] + $all_param['lost']));
            // if ($all_param['match_times'] > 3) {
            //     return self::bulidFail('胜平负的场次之和不能超过3场');
            // }
            // 净胜球 = 进球数 - 失球数，可以为负整数
            $all_param['goal_difference'] = $all_param['goals'] - $all_param['goals_conceded'];
            // 积分计算：赢球积3分，平局双方各积1分，输球积0分
            // $all_param['score'] = bcmul($all_param['win'], 3) + bcmul($all_param['draw'], 1);

            if ($point_info->save($all_param)) {
                // 记录日志
                $log_content = "编辑球队积分，球队：{$point_info->team_name}";
                parent::addAdminLog($log_content);

                return parent::bulidSuccess();
            }
            return parent::bulidFail();
        }

        $this->assign('point_info', $point_info);
        return $this->fetch();
    }

    /**
     * 晋级图
     */
    public function rank()
    {
        // 获取世界杯晋级赛事
        $match_rank = WorldCupMatchRankModel::where('rank_type', '>', 0)->order("rank_type")->select()->toArray();
        $this->assign('match_rank', $match_rank);
        return $this->fetch();
    }

    public function rank_add()
    {
        $match_list = WorldCupMatchModel::where("group_code!=''")->select();

        $matches = [];
        foreach ($match_list as $key => $value) {
            $matches[] = ['team_id' => $value['home_team_id'], 'team_name' => $value['home_team_name'], 'team_logo' => $value['home_team_logo']];
            $matches[] = ['team_id' => $value['away_team_id'], 'team_name' => $value['away_team_name'], 'team_logo' => $value['away_team_logo']];
        }

        $this->assign('match_list', $matches);
        return $this->fetch();
    }

    public function rank_add_handle()
    {
        $home = Request::param('home');
        $away = Request::param('away');
        $rank_type = Request::param('rank_type');

        if ($home == "" || $away == "" || $rank_type == "") {
            return self::bulidFail('数据错误');
        }
        $model = new WorldCupMatchRankModel();

        $home = explode("|", $home);
        $away = explode("|", $away);
        $model->home = $home[1];
        $model->home_logo = $home[2];
        $model->away = $away[1];
        $model->away_logo = $away[2];

        $model->rank_type = $rank_type;

        if ($model->save()) {
            return parent::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function rank_del()
    {
        $id = Request::param('id');
        if ($id <= 0) {
            return self::bulidFail('赛事错误');
        }

        WorldCupMatchRankModel::where("id", $id)->delete();
        return parent::bulidSuccess();
    }

    /**
     * 晋级图赛事更新
     */
    public function rank_edit()
    {
        $match_id = Request::param('match_id', 0, 'intval');
        if ($match_id < 1) {
            return self::bulidFail('赛事id错误,请刷新重试');
        }
        // 查询赛事信息
        $match_info = WorldCupMatchRankModel::with('matchInfo')->where('match_id', $match_id)->find();
        if (!$match_info) {
            return self::bulidFail('未查询到赛事信息');
        }

        // 主队客队标示
        list($home_team, $away_team) = $this->getHomeAwayFlag($match_info->match_flag);

        $rank_data  = [
            $home_team . '_name'                   => $match_info->match_info->home,
            $home_team . '_name_logo'              => $match_info->match_info->home_logo,
            $away_team . '_name'                   => $match_info->match_info->away,
            $away_team . '_name_logo'              => $match_info->match_info->away_logo,
            "{$match_info->match_flag}_match_time" => $match_info->match_info->match_time,
        ];

        if (!empty($match_info->match_info->footballmatch->hometeam->country_logo)) {
            $rank_data[$home_team . '_name_logo'] = $match_info->match_info->footballmatch->hometeam->country_logo;
        }
        if (!empty($match_info->match_info->footballmatch->awayteam->country_logo)) {
            $rank_data[$away_team . '_name_logo'] = $match_info->match_info->footballmatch->awayteam->country_logo;
        }

        $rank_model = WorldCupRankModel::get(1);
        if ($rank_model->save($rank_data)) {
            // 记录日志
            $log_content = "更新晋级图，球队：{$match_info->match_info->home} VS {$match_info->match_info->away}";
            parent::addAdminLog($log_content);

            return parent::bulidSuccess();
        }
        return self::bulidFail();
    }

    /**
     * 晋级图-球队淘汰设置
     */
    public function rank_lose()
    {
        $match_id  = Request::param('match_id', 0, 'intval');
        $lose_flag = Request::param('lose_flag');
        if ($match_id < 1 || !$lose_flag) {
            return self::bulidFail('赛事信息错误,请刷新重试');
        }

        // 查询赛事信息
        $match_info = WorldCupMatchRankModel::with('matchInfo')->where('match_id', $match_id)->find();
        if (!$match_info) {
            return self::bulidFail('未查询到赛事信息');
        }

        // 主队客队标示
        list($home_team, $away_team) = $this->getHomeAwayFlag($match_info->match_flag);

        if (!in_array($lose_flag, [$home_team, $away_team])) {
            return self::bulidFail('赛事信息错误,请刷新重试');
        }

        $rank_data  = [
            $home_team . '_status' => $lose_flag == $home_team ? 2 : 1,
            $away_team . '_status' => $lose_flag == $away_team ? 2 : 1,
        ];
        $rank_model = WorldCupRankModel::get(1);

        Db::startTrans();
        try {
            if (!$rank_model->save($rank_data)) {
                throw new \Exception('修改失败');
            }

            if (!$match_info->save(['lose_flag' => $lose_flag])) {
                throw new \Exception('修改失败');
            }

            // 记录日志
            $log_content = "设置球队淘汰，比赛球队：{$match_info->match_info->home} VS {$match_info->match_info->away}，淘汰球队：";
            $log_content .= $lose_flag == $home_team ? $match_info->match_info->home : $match_info->match_info->away;
            parent::addAdminLog($log_content);

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()], '设置失败');
        }

        return self::bulidFail();
    }


    /**
     * 晋级图-球队淘汰重置
     */
    public function reset_lose()
    {
        $match_id = Request::param('match_id', 0, 'intval');
        if ($match_id < 1) {
            return self::bulidFail('赛事信息错误,请刷新重试');
        }

        // 查询赛事信息
        $match_info = WorldCupMatchRankModel::with('matchInfo')->where('match_id', $match_id)->find();
        if (!$match_info) {
            return self::bulidFail('未查询到赛事信息');
        }

        // 主队客队标示
        list($home_team, $away_team) = $this->getHomeAwayFlag($match_info->match_flag);

        $rank_data  = [
            $home_team . '_status' => 1,
            $away_team . '_status' => 1,
        ];
        $rank_model = WorldCupRankModel::get(1);

        Db::startTrans();
        try {
            if (!$rank_model->save($rank_data)) {
                throw new \Exception('修改失败');
            }

            if (!$match_info->save(['lose_flag' => ''])) {
                throw new \Exception('修改失败');
            }

            // 记录日志
            $log_content = "重置球队淘汰，球队：{$match_info->match_info->home} VS {$match_info->match_info->away}";
            parent::addAdminLog($log_content);

            Db::commit();
            return self::bulidSuccess();
        } catch (\Exception $e) {
            Db::rollback();
            return self::bulidDataFail(['error' => $e->getMessage()], '设置失败');
        }

        return self::bulidFail();
    }

    /**
     * 晋级图获取主客标示，方便更新晋级图配置表
     * @param $match_flag
     * @return array
     */
    private function getHomeAwayFlag($match_flag)
    {
        if (empty($match_flag)) {
            return ['', ''];
        }

        $match_flag = explode('_', $match_flag);
        // 主队客队标示
        $home_team = '';
        $away_team = '';
        if (count($match_flag) == 2) {
            $home_team = $match_flag[0];
            $away_team = $match_flag[1];
        } else if (count($match_flag) == 3) {
            $home_team = $match_flag[0] . '_' . $match_flag[2];
            $away_team = $match_flag[1] . '_' . $match_flag[2];
        }
        return [$home_team, $away_team];
    }
}
